//% color="#FF6347" iconWidth=45 iconHeight=45
namespace LLMAssistant {

    //% block="初始化模型 API地址[API_URL] API密钥[API_KEY] 模型[MODEL]" blockType="command"
    //% API_URL.shadow="string" API_URL.defl="https://api.deepseek.com"
    //% API_KEY.shadow="string" API_KEY.defl="api_key"
    //% MODEL.shadow="string" MODEL.defl="deepseek-chat"
    export function initializeLLM(parameter: any) {
        const apiUrl = parameter.API_URL.code;
        const apiKey = parameter.API_KEY.code;
        const model = parameter.MODEL.code;

        Generator.addImport(`import requests\nimport json\nfrom pathlib import Path\nimport base64`);
        
        Generator.addDeclaration(`LLMChat`,`
class LLMChat:
    def __init__(self):
        base_url = ${apiUrl}.rstrip('/')
        if base_url.endswith('/chat/completions'):
            self.api_url = base_url
        else:
            self.api_url = f"{base_url}/chat/completions"
        self.api_key = ${apiKey}
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
        self.messages = [{"role": "user", "content": "回答简短，不要出现emoji表情"}]
        self.model = ${model}
    def dfrobot_chat_image(self, image_path):
        try:
            with open(image_path, "rb") as image_file:
                base64_image = base64.b64encode(image_file.read()).decode('utf-8')
            
            image_content = {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/png;base64,{base64_image}"
                }
            }
            self.messages.append({
                "role": "user",
                "content": [image_content]
            })
        except Exception as e:
            print("图片处理失败: {str(e)}")

    def dfrobot_chat(self, user_input):
        
        self.messages.append({"role": "user", "content": user_input})
        
        payload = {
            "model": self.model,
            "messages": self.messages
        }
        try:
            response = requests.post(
                url=self.api_url,
                headers=self.headers,
                data=json.dumps(payload)
            )
            if response.status_code == 200:
                response_data = response.json()
                ai_response = response_data['choices'][0]['message']['content']
                self.messages.append({"role": "assistant", "content": ai_response})
                return ai_response
            else:
                return f"Error: {response.status_code} - {response.text}"
        except Exception as e:
            return f"Exception: {str(e)}"


bot = LLMChat()`);
    }

    //% block="发送消息[MESSAGE] 并返回响应" blockType="reporter"
    //% MESSAGE.shadow="string" MESSAGE.defl="你好"
    export function sendMessage(parameter: any, block: any) {
        const message = parameter.MESSAGE.code;
        Generator.addCode(`bot.dfrobot_chat(${message})`);
    }

    //% block="---"
    export function noteSep() {}
    //% block="多模态功能(支持图片理解的模型可用)" blockType="tag"
    export function tagtest() {}    

    //% block="上传图片[dfrobot_image_path]" blockType="command"
    //% dfrobot_image_path.shadow="string" dfrobot_image_path.defl="xxx.png"
    export function uploadImage(parameter: any, block: any) {
        const  image_path= parameter.dfrobot_image_path.code;
        Generator.addCode(`bot.dfrobot_chat_image(${image_path})`);
    }
}